/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.sample;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.webos.java.base.Frame;
import org.webos.java.base.FrameType;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.workspace.Workspace;
import org.webos.java.root.Log;

/**
 *
 * @author kostya
 */
@FrameType(code="tree", jsClass="sample.TreeFrame")
public class TreeFrame extends Frame{

    List<ABEntry> entries = new ArrayList<ABEntry>();
    ABEntry selected = null;
    private AddressBookApplication app = null;

    public TreeFrame(AddressBookApplication app, Workspace ws) {
        super(app, ws);
        this.app = app;
        setIcon("ab_icons ab_icon");
        setTitle("Addressbook:");
        try {
            if(app.connection.isActive()){
                PreparedStatement st = app.connection.getConnection().prepareStatement("select * from entries order by lastname");
                ResultSet rset = st.executeQuery();
                while(rset.next()){
                    ABEntry entry = new ABEntry();
                    entry.id = rset.getInt("id");
                    entry.lastName = rset.getString("lastname");
                    entry.firstName = rset.getString("firstname");
                    entry.email = rset.getString("email");
                    entry.work_email = rset.getString("work_email");
                    entry.work_phone = rset.getString("work_phone");
                    entry.home_phone = rset.getString("home_phone");
                    entry.cell_phone = rset.getString("cell_phone");
                    entry.birthday = rset.getString("birthday");
                    entry.notes = rset.getString("notes");
                    entries.add(entry);
                }
                if(entries.size()>0)
                    selected = entries.get(0);
                st.close();
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
    }

    @RemoteMessage
    public void selectEntry(JSONObject data){
        try {
            int id = data.optInt("id", 0);
            for (ABEntry entry : entries) {
                if(entry.id==id){
                    boolean newSelect = !entry.equals(selected);
                    selected = entry;
                    JSONObject obj = new JSONObject();
                    obj.put("lastName", entry.lastName);
                    obj.put("firstName", entry.firstName);
                    obj.put("work_email", entry.work_email);
                    obj.put("work_phone", entry.work_phone);
                    obj.put("home_phone", entry.home_phone);
                    obj.put("cell_phone", entry.cell_phone);
                    obj.put("birthday", entry.birthday);
                    obj.put("notes", entry.notes);
                    obj.put("id", entry.id);
                    app.mainFrame.sendMessage("editEntry", obj);
                    if(newSelect)
                        app.showFrame(app.mainFrame);
                }
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
    }

    void newEntry(){
        Log.debug(this, "Create new entry");
        try {
            if(app.connection.isActive()){
                Log.debug(this, "Connection is opened");
                String query = "insert into entries (lastname) values ('')";
                Statement st = app.connection.getConnection().createStatement();
                st.execute(query);
                Log.debug(this, "Query executed");
                st.close();
                selected = new ABEntry();
                selected.id = app.connection.getLastID();
                Log.debug(this, "Last ID is "+selected.id);
                entries.add(selected);
                sendMessage("reloadTree", getEntries(null));
            }else{
                Log.debug(this, "connection is closed");
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
    }

    @RemoteMessage
    public JSONObject getEntries(JSONObject data){
        try {
            JSONArray arr = new JSONArray();
            for (ABEntry entry : entries) {
                JSONObject obj = new JSONObject();
//                Log.debug(this, "Entry:", entry.firstName, entry.lastName);
                if((entry.firstName==null ||  entry.firstName.equals("")) && (entry.lastName==null || entry.lastName.equals("")))
                    obj.put("name", "&lt;New contact&gt;");
                else
                    obj.put("name", entry.firstName+" "+entry.lastName);
                obj.putOpt("icon", "ab_icons ab_single");
                obj.put("id", entry.id);
                arr.put(obj);
            }
            JSONObject resp = new JSONObject();
            resp.put("data", arr);
            if(selected!=null)
                resp.put("selected", selected.id);
            return resp;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @RemoteMessage
    public void openDlg(JSONObject obj){
        Log.debug(this, "Creating new dialog");
        boolean res = getApplication().getSession().addDialog(new Dialog1(getApplication()));
        Log.debug(this, "Result: "+res);
    }
}
